import WxValidate from "wechat-validate";
Page({
  behaviors: [WxValidate],
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    minDate: Date.now(),
    maxDate: Date.now() + 3 * 24 * 3600 * 1000, // 今天开始往后数三天的时间多
    houseList: [],
    houseId: "", // 选中的房屋id
    houseInfo: "", // 选中的房屋名字
    visitDate: "", // 访客到访时间，和接口字段保持一致
    name: "", // 访客姓名
    gender: 1, // 访客性别
    mobile: "", // 手机号
  },
  rules: {
    name: [
      { required: true, message: "访客姓名不能为空!" },
      { pattern: /[\u4e00-\u9fa5]{2,5}/, message: "访客姓名只能为中文!" },
    ],
    mobile: [
      { required: true, message: "访客手机号不能为空!" },
      { pattern: /^1[3-9]\d{9}$/, message: "请填写正确的手机号码!" },
    ],
    houseId: [{ required: true, message: "请选择到访的房屋!" }],
    visitDate: [{ required: true, message: "请选择到访的日期!" }],
  },
  onLoad() {
    this.getHouseList();
  },
  async getHouseList() {
    const { code, data } = await wx.http.get("/house");
    if (code !== 10000) return wx.utils.toast();
    this.setData({
      houseList: data,
    });
  },
  selectHouse(e) {
    console.log(e);
    // 把用户选中的房屋信息存储到data里面，目的是提交的时候需要，数据回显的时候需要
    this.setData({
      houseId: e.detail.id,
      houseInfo: e.detail.name,
    });
  },
  selectDate(e) {
    this.setData({
      visitDate: wx.utils.dataFormat(e.detail),
      dateLayerVisible: false, // 选择完时间之后，关闭时间弹层
    });
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true });
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false });
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true });
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false });
  },
  async goPassport() {
    // 1、表单校验
    if (!this.validate()) return;
    // 2、接口需要的字段从data里面结构出来
    const { houseId, mobile, name, visitDate, gender } = this.data;
    // 3、调用接口提交当前访客数据
    const {
      code,
      data: { id },
    } = await wx.http.post("/visitor", {
      houseId,
      mobile,
      name,
      visitDate,
      gender,
    });
    if (code !== 10000) return wx.utils.toast("创建访客失败");
    // 4、后端会返回当前这条数据的id，跳转二维码页面的时候需要携带id跳转
    wx.reLaunch({
      url: "/visitor_pkg/pages/passport/index?id=" + id,
    });
  },
});
